package com.heima.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.crm.annotation.AddNotice;
import com.heima.crm.common.result.PageResult;
import com.heima.crm.common.result.Result;
import com.heima.crm.common.utils.AliOssUtil;
import com.heima.crm.common.utils.BaseContext;
import com.heima.crm.enumeration.OperationType;
import com.heima.crm.mapper.ContractMapper;
import com.heima.crm.mapper.TbActivityMapper;
import com.heima.crm.mapper.TbCourseMapper;
import com.heima.crm.pojos.dtos.ContractPageDto;
import com.heima.crm.pojos.entity.TbActivity;
import com.heima.crm.pojos.entity.TbContract;
import com.heima.crm.pojos.entity.TbCourse;
import com.heima.crm.service.ContractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * 合同相关接口
 */
@Service
@Slf4j
public class ContractServiceImpl implements ContractService {
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private TbActivityMapper tbActivityMapper;
    @Autowired
    private TbCourseMapper tbCourseMapper;

    /**
     * 合同分页查询
     *
     * @param contractPageDto
     * @return
     */
    @Override
    public Result pageQurry(ContractPageDto contractPageDto) {
        if (contractPageDto.getPage() <= 0 || contractPageDto.getPage() == null) {
            contractPageDto.setPage(1);

        }
        if (contractPageDto.getPageSize() <= 0 || contractPageDto.getPageSize() == null) {
            contractPageDto.setPageSize(10);

        }
        Page page = new Page(contractPageDto.getPage(), contractPageDto.getPageSize());
        LambdaQueryWrapper<TbContract> lqw = new LambdaQueryWrapper<>();
        if (contractPageDto.getContractId() != null && contractPageDto.getContractId() != "") {
            lqw.like(TbContract::getContractId, contractPageDto.getContractId());
        }
        if (contractPageDto.getCustomName() != null && contractPageDto.getCustomName() != "") {
            lqw.like(TbContract::getCustomName, contractPageDto.getCustomName());
        }
        if (contractPageDto.getTel() != null && contractPageDto.getTel() != "") {
            lqw.like(TbContract::getTel, contractPageDto.getTel());
        }
        if (contractPageDto.getSubjectId() != null) {
            lqw.eq(TbContract::getSubjectId, contractPageDto.getSubjectId());
        }
        if (contractPageDto.getCourseId() != null) {
            lqw.eq(TbContract::getCourseId, contractPageDto.getCourseId());
        }
        if (contractPageDto.getMinTime() != null) {
            LocalDateTime minTime = contractPageDto.getMinTime().atStartOfDay();
            lqw.ge(TbContract::getCreateTime, minTime);
        }
        if (contractPageDto.getMaxTime() != null) {
            LocalDateTime maxTime = contractPageDto.getMaxTime().atTime(23, 59, 59);
            lqw.le(TbContract::getCreateTime, maxTime);
        }
        lqw.orderByDesc(TbContract::getCreateTime);
        page = contractMapper.selectPage(page, lqw);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getRecords());
        return Result.success(pageResult);
    }

    /**
     * 合同详情
     *
     * @param id
     * @return
     */
    @Override
    public Result display(Integer id) {
        TbContract tbContract = contractMapper.selectById(id);

        return Result.success(tbContract);
    }

    /**
     * 合同文件上传
     *
     * @param file
     * @return
     */
    @Override
    public Result upload(MultipartFile file) {
        //先判断是不是pdf文件
        String originalFilename = file.getOriginalFilename();
        //文件名后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!".pdf".equals(suffix)) {
            return Result.error("文件格式不正确,请上传PDF格式文件");
        }
        //上传
        String fileName = UUID.randomUUID().toString() + suffix;
        String url = null;
        try {
            url = aliOssUtil.upload(file.getBytes(), fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //回填
        return Result.success(url);
    }

    /**
     * 新增合同
     *
     * @param tbContract
     * @return
     */
    @Override
    @AddNotice(OperationType.CONTRACT)
    public Result insert(TbContract tbContract) {
        //价格,是否活动,活动信息
        //根据课程查到初始价格
        //判断合同编号是否重复
        String contractId = tbContract.getContractId();
        LambdaQueryWrapper<TbContract> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TbContract::getContractId, contractId);
        TbContract tbContract1 = contractMapper.selectOne(lambdaQueryWrapper);
        if (tbContract1 != null) {
            return Result.error("合同编号已存在!");
        }
        // 定义手机号码的正则表达式
        String regex = "^1[3-9]\\d{9}$";
        // 创建Pattern对象
        Pattern pattern = Pattern.compile(regex);
        // 使用Pattern对象匹配手机号码
        boolean matches = pattern.matcher(tbContract.getTel()).matches();
        if (!matches) {
            return Result.error("请输入11位正确的手机号码!");

        }
        TbCourse tbCourse = tbCourseMapper.selectById(tbContract.getCourseId());
        double price = tbCourse.getPrice().doubleValue();
        tbContract.setCount(price);
        tbContract.setIsDiscount((short) 0);
        tbContract.setCourseName(tbCourse.getName());
        setSubjectName(tbContract, tbCourse);
        //判断有没有活动,在看后续信息
        if (tbContract.getSaleMassageId() != null) {
            TbActivity tbActivity = tbActivityMapper.selectById(tbContract.getSaleMassageId());
            tbContract.setDiscountType(tbActivity.getName());
            tbContract.setIsDiscount((short) 1);
            //折扣
            if (tbActivity.getType() == 1) {
                if (tbActivity.getDiscount() < 1) {
                    tbContract.setCount(price * tbActivity.getDiscount());
                    log.info(String.valueOf((price * tbActivity.getDiscount())));
                } else {
                    tbContract.setCount(price * tbActivity.getDiscount() * 0.1);
                    log.info(String.valueOf(price * tbActivity.getDiscount() * 0.1));
                }
            } else {
                tbContract.setCount(price - tbActivity.getVouchers());
                log.info(String.valueOf(price - tbActivity.getVouchers()));

            }
        }
        tbContract.setCreateTime(LocalDateTime.now());
        tbContract.setCreateId(BaseContext.getCurrentId());
        if (tbContract.getIsTransform() == null) {
            tbContract.setIsTransform((short) 0);
        }
        tbContract.setIsTransform((short) 1);
        contractMapper.insert(tbContract);
        return Result.success();
    }

    private void setSubjectName(TbContract tbContract, TbCourse tbCourse) {
        if (tbCourse.getSubject() == 0) {
            tbContract.setSubjectName("Java");
        }
        if (tbCourse.getSubject() == 1) {
            tbContract.setSubjectName("前端");
        }
        if (tbCourse.getSubject() == 2) {
            tbContract.setSubjectName("人工智能");
        }
        if (tbCourse.getSubject() == 3) {
            tbContract.setSubjectName("大数据");
        }
        if (tbCourse.getSubject() == 4) {
            tbContract.setSubjectName("Python");
        }
        if (tbCourse.getSubject() == 6) {
            tbContract.setSubjectName("测试");
        }
        if (tbCourse.getSubject() == 7) {
            tbContract.setSubjectName("新媒体");
        }
        if (tbCourse.getSubject() == 8) {
            tbContract.setSubjectName("产品经理");
        }
        if (tbCourse.getSubject() == 9) {
            tbContract.setSubjectName("UI设计");
        }
    }

    /**
     * 合同预览
     *
     * @param id
     * @return
     */
    @Override
    public Result preview(Long id) {
        TbContract tbContract = contractMapper.selectById(id);
        return Result.success(tbContract.getContractUrl());
    }


}
